package cn.fr4nk.crawler.thread;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.fr4nk.crawler.task.Handler;

public class CrawlerTaskThreadPool<T> extends ThreadPool {
	
	private static Log log = LogFactory.getLog(CrawlerTaskThreadPool.class);

	private Handler<T> handler;

	private String handlerRunnableClazz;

	@SuppressWarnings("unchecked")
	public HandlerRunnable<T> createRunnable() throws Exception {
		log.debug("[Pool] 创建runnable:" + handlerRunnableClazz);
		HandlerRunnable<T> res = null;
		if (StringUtils.isNotEmpty(handlerRunnableClazz)) {
			Class<HandlerRunnable<T>> clz = (Class<HandlerRunnable<T>>) Class.forName(handlerRunnableClazz);
			res = clz.newInstance();
			res.setHandler(handler);
			log.debug("[Pool] 创建runnable new Instance:" + res);
		} else {
			throw new NullPointerException("无效配置的类名：null or empty str");
		}
		return res;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		// TODO Auto-generated method stub
		super.afterPropertiesSet();
		for (int i = 0; i < poolSize; i++) {
			try {
				HandlerRunnable<T> r = createRunnable();
				addRunnable(r);
				log.debug("[Pool] 将runnable 加入pool成功" );
			} catch (Exception e) {
				log.warn("创建HandlerRunnable失败："+e.getMessage());
				throw e;
			}
		}
	}

	public Handler<T> getHandler() {
		return handler;
	}

	public void setHandler(Handler<T> handler) {
		this.handler = handler;
	}

	public String getHandlerRunnableClazz() {
		return handlerRunnableClazz;
	}

	public void setHandlerRunnableClazz(String handlerRunnableClazz) {
		this.handlerRunnableClazz = handlerRunnableClazz;
	}

}
